package gui;

import javax.swing.*;
import java.awt.*;
import java.awt.geom.Ellipse2D;

public class RoundButton extends JButton
{
	private Shape shape;
	
	/**
	 * Constructor with only one image. This image will be used as active and inactive icon.
	 * 
	 * @param activeIcon the image for active and inactive state
	 */
    public RoundButton(Icon activeIcon) 
    {
        this(activeIcon, activeIcon);
    }
    
    /**
     * Constructor with all parameters.
     * 
     * @param text the button's text
     * @param activeIcon the image which will be shown on mouse over event
     * @param inactiveIcon the image that will otherwise be shown
     */
    public RoundButton(Icon activeIcon, Icon inactiveIcon) 
    {
        setIcon(inactiveIcon);
        setRolloverIcon(activeIcon);
        setPressedIcon(activeIcon);
        
        int iw = Math.max(inactiveIcon.getIconWidth(), inactiveIcon.getIconHeight());
        int sw = 1;
        // create a one pixel wide border around the button
        setBorder(BorderFactory.createEmptyBorder(sw, sw, sw, sw));
        // the dimension is the image size plus a one pixel border
        Dimension dim = new Dimension(iw+sw*2, iw+sw*2);
        setPreferredSize(dim);
        setMinimumSize(dim);
        setMaximumSize(dim);
        setBackground(Color.BLACK);
        setContentAreaFilled(false);
        setFocusPainted(false);
        setAlignmentY(Component.TOP_ALIGNMENT);
        // the round shape of the button must be set in order to handle mouse moves correctly
        initShape();
    }
    
    protected void initShape() 
    {
    	Dimension s = this.getPreferredSize();
    	shape = new Ellipse2D.Float(0, 0, s.width-1, s.height-1);
    }
    
    @Override
    protected void paintBorder(Graphics g) 
    {
        initShape();
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(getBackground());
        g2.draw(shape);
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
    }
    
    @Override
    public boolean contains(int x, int y) 
    {
    	/*
    	 *  This method returns true, if the mouse cursor is positioned inside the circle.
    	 *  Otherwise it returns false.
    	 */
        if(shape == null) initShape();
        return shape.contains(x, y);
    }
}